import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'

// 不需要前端模拟数据,数据经过后端从数据库查出来,所以注释掉
// import Mock from './mock'
// Mock.bootstrap();
//引入axios
import axios from 'axios'
import 'font-awesome/css/font-awesome.min.css'
//配置axios的全局基本路径，访问后端接口使用8080
axios.defaults.baseURL='http://localhost:8080/' // 连接后端接口,其实就是Controller
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})



//======================axios的前置拦截器====================//
//每次路由请求之前：将token设置到请求头 -  token携带到后端
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token"); // 获取token
  if(token){
    //将token放入请求头
    res.headers["token"] = token;
  }
  return res; // 请求头中携带token传到后端
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器====================//




//======================axios的后置拦截器====================//
//处理后端响应的数据 - 跳转页面
axios.interceptors.response.use(res=>{
  let data = res.data;
  // 如果data里有msg为noLogin,说明没有登陆
  if(data.msg==="noLogin") {
    // 通过路由跳转到login页面
    this.$router.push({ path: '/login' });
  }
  return res;
},error => {
  Promise.reject(error);
})
//======================axios的后置拦截器====================//




//======================axios的前端拦截器====================//
//拦截不经过后端的请求 - 直接访问页面
router.beforeEach((to, from, next) => {
  // 如果访问login或者shopRegister页面
  if (to.path == '/login' || to.path == "/shopRegister") {
    // localStorage删除token和logininfo
    localStorage.removeItem('token');
    localStorage.removeItem('logininfo');
    next();//放行
  }else{
    // 访问login或者shopRegister以外的页面
    // 从localStorage中获取logininfo(后端LogininfoServiceImpl中map里put的logininfo对象)
    let logininfo = localStorage.getItem('logininfo');
    if (logininfo) {
      // 如果获取到了logininfo,则放行
      next() //放行
    } else {
      // 如果没有获取到logininfo,则拦截
      next({path: '/login'});//跳转到login
    }
  }
})
//======================axios的前端拦截器====================//



//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

